import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    // 查询关键词
    query: '',
    // 分类ID
    cid: '',
    // 页数索引
    pagenum: 1,
    // 每页显示个数
    pagesize: 10,
    // 商品列表数据
    goodsList: [],
    // 商品总条数
    total: 0,
    // 判断页面是否到达底部
    isover: false,
    // 判断当前页面数据是否加载完成
    isloading: false
  }

  onLoad(options) {
    // console.log(options)
    this.query = options.query || ''
    this.cid = options.cid || ''

    // 调用获取商品列表的方法
    this.getGoodsList()
  }

  onReachBottom () {
    if(this.isloading) {
      return
    }

    if (this.pagenum * this.pagesize >= this.total) {
      // 为什么需要在这个里面重新赋值
      // 因为这时候数据已经完成加载完成了
      this.isover = true
      return
    }

    this.pagenum++
    this.getGoodsList()
  }

  onPullDownRefresh	() {
    this.pagenum = 1
    this.total = 0
    this.isover = this.isloading = false
    this.goodsList = []
    this.getGoodsList(() => {
      wepy.stopPullDownRefresh()
    })
  }

  // 获取商品列表的方法
  async getGoodsList (cb) {
    this.isloading = true
    const { data: res } = await wepy.get('/goods/search', {
      query: this.query,
      cid: this.cid,
      pagenum: this.pagenum,
      pagesize: this.pagesize
    })

    // 判断返回的数据是否成功
    if (res.meta.status !== 200) {
      return wepy.baseToast()
    }

    this.goodsList = [...this.goodsList, ...res.message.goods]
    this.total = res.message.total
    this.isloading = false
    this.$apply()
    cb && cb()
  }

  methods = {
    goGoodsDetail (goodsId) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id=' + goodsId
      })
    }
  }
}
